"""
2023-11-08 产品确认不再执行该脚本
"""
import copy
import arrow

from pymongo import MongoClient, InsertOne, UpdateOne

from conf.settings import (
    CLOUDMONITOR_MONGODB,
    CLOUDMONITOR_DB,
)
from utility.log import Logger
logger = Logger(filename='user_add_ipv6.log').get_logger()

db = MongoClient(CLOUDMONITOR_MONGODB)[CLOUDMONITOR_DB]

ARROW_UTC_NOW = arrow.utcnow()
ARROW_NOW = ARROW_UTC_NOW.shift(hours=8)

BASE_TPL = {
    "limitType": "limit",
    "used": 0,
    "total": 50,
    "number": 0,
    "time": 0,
    "taskType": "ipv6",
}

BALANCES_UPDATE_DICT = {'balance.ipv6ManualTask': BASE_TPL, 'feature.ipv6ManualTask': True}

CHARGES_INSERT_DICT = {
    **BASE_TPL,
    'number': 1,
    'isDelete': False,
    "funcType": "ipv6ManualTask",
    "packId": None,
    "uid": None,
    "chargeType": "plan",
    "createTime": ARROW_UTC_NOW.datetime,
    "updateTime": ARROW_UTC_NOW.datetime,
}


def get_uid_exp_list():
    # from bson import ObjectId

    return [(item.get('uid'), item.get('planExpireTime'), item.get('planId')) for item in db.balances.find({
        'planExpireTime': {'$gt': ARROW_NOW.datetime},
        '$or': [{'balance.ipv6ManualTask': {'$exists': 0}}, {'balance.ipv6ManualTask.total': 0}]
        # 'uid': ObjectId('609b3a87b231ba001bba26b0')
    })]


def add(uid_exp_list: list):
    balances_update_list = []
    charges_insert_list = []
    for uid, exp, plan_id in uid_exp_list:
        balances_update_list.append(UpdateOne({'uid': uid}, {'$set': BALANCES_UPDATE_DICT}))
        insert_dict = copy.deepcopy(CHARGES_INSERT_DICT)
        insert_dict.update({'uid': uid, 'expireTime': exp, 'packId': plan_id})
        charges_insert_list.append(InsertOne(insert_dict))

    if balances_update_list:
        db.balances.bulk_write(balances_update_list)
    if charges_insert_list:
        db.charges.bulk_write(charges_insert_list)


def main():
    logger.info("Start.")
    uid_exp_list = get_uid_exp_list()
    add(uid_exp_list)
    logger.info("Complete.")


if __name__ == '__main__':
    main()
